#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__title__ = ''
__author__ = 'HaiFeng'
__mtime__ = '2016/8/16'
"""
import talib

from py_at.Enums import *
from py_at.Data import Data
from py_at.Bar import Bar

import time
from py_at.strategy import Strategy

class SMACross(Strategy):
    def __init__(self,cfg):
        super().__init__(cfg)
        # 初始化默认参数
        if (cfg==""):
            self.Params['MA1'] = 5
            self.Params['MA2'] = 10
            self.Params['Lots'] = 1
            self.Params['Slippage']=1
        self.p_ma1 = self.Params['MA1']
        self.p_ma2 = self.Params['MA2']
        self.p_lots = self.Params['Lots']
        self.Slippage = self.Params['Slippage']
        self.timeD=''

    def OnBarUpdate(self, data=Data, bar=Bar):

        # print('时间{0}收盘价格{1}总k线数据'.format(self.D, self.C, len(self.C)))
        # if len(self.C) == 1:       # 第一根bar
        #     self.UpdateParams()

        if len(self.C) < self.p_ma2:     # 如果bar数目小于 p._ma2参数  退出
            return
        ma1 = talib.MA(self.C, self.p_ma1)
        ma2 = talib.MA(self.C, self.p_ma2)
        if(self.timeD!=self.D[-1]):
            self.IndexDict['ma5']= ma1.tolist()
            self.IndexDict['ma10']= ma2.tolist()

            self.timeD = self.D[-1]
        if self.PositionLong == 0:    # 多仓等于0  上传
            if ma1[-2] > ma2[-2] and ma1[-3] < ma2[-3]:
                #self.writeStrategyLog("已经上传 %s"  %self.timeD);
                if self.PositionShort > 0:     # 如果有空仓
                    #self.writeStrategyLog("当前仓位为-1所以先平掉 买平");
                    self.BuyToCover(self.O[-1]+self.Slippage*self.PriceTick, self.p_lots, '买平')  # 平空 当前k收盘
                self.Buy(self.O[-1]+self.Slippage*self.PriceTick, self.p_lots, '买开')     # 买多
                #self.writeStrategyLog("开多")
        elif self.PositionShort == 0:
            if ma1[-2] < ma2[-2] and ma1[-3] > ma2[-3]:
                print('卖')
                #self.writeStrategyLog("已经下传 %s" %self.timeD);
                if self.PositionLong > 0:
                    #self.writeStrategyLog("当前仓位为1所以先平掉 卖平");
                    self.Sell(self.O[-1]-self.Slippage*self.PriceTick, self.p_lots, '卖平')
                self.SellShort(self.O[-1]-self.Slippage*self.PriceTick, self.p_lots, '卖开')
                #self.writeStrategyLog("开空");

